import cherrypy
import sqlite3
import time
import Common

from postmarkup import render_bbcode

class Search(Common.Template):
	
	def index(self):
		return self.default()
	index.exposed = True
		
	def default(self, q = None):
		# if the user didn't search for anything
		if q is None or q == '':
			# return an error
			yield self.error('Please enter valid search terms.')
		else:
			# build a query from the search terms
			expr = '''
				SELECT
					Post.ID, Post.Title, Post.Content, Post.Timestamp, User.ID, User.Username, User.Permission, User.Avatar, User.Signature, Post.EditTimestamp, Post.EditUserID
				FROM
					Post, User
				WHERE
					User.ID = Post.UserID AND 
			'''
			# place ANDs between each term
			for term in q.split(' '):
				expr += '''
					Post.Content like "%''' + term + '''%" AND
				'''
			expr = expr.rstrip('\n\tAND') + '''
				ORDER BY
					Post.EditTimestamp DESC
			'''
			cursor = cherrypy.thread_data.db.cursor()
			cursor.execute(expr)
			# return the search results
			res = cursor.fetchall()
			yield self.header()
			yield self.links()
			yield self.breadcrumbs()
			yield '<h2>Search Results for "%s"</h2>' % q
			# if there are no results
			if len(res) == 0:
				yield '<p>No results.</p>'
			else:
				# copied with modifications from Thread.py
				count = 1
				permissions = ["Administrator", "Moderator", "Member"]
				for ID, Title, Content, Timestamp, UserID, Username, Permission, Avatar, Signature, EditTimestamp, EditUserID in res:
					# link in corner takes the user to the actual thread and post
					tid = self.getThreadID(ID)
					yield "<table width='100%' cols='2' class='thread' >"
					yield "<tr>"
					yield "<td class='thread' colspan='2'><a name='%s'></a>%s <span style='float:right; text-align: right;'><a href='/Thread/%s#%s'>#%s</a></span></td>" % (ID, Title, tid, ID, count)
					yield "</tr>"
					yield "<tr>"
					if Avatar == "" or Avatar == None:
						yield "<td class='thread' rowspan='3' width='200px'><a href='/User/%s'>%s</a><br />%s<br /><div width='100px' height='100px'>&nbsp;</div></td><td class='thread' height='75px' >%s</td>" % (UserID, Username, permissions[Permission], render_bbcode(Content))
					else:
						yield "<td class='thread' rowspan='3' width='200px'><a href='/User/%s'>%s</a><br />%s<br /><img src='/%s' width='100px' height='100px' /></td><td class='thread' height='75px' >%s</td>" % (UserID, Username, permissions[Permission], Avatar, render_bbcode(Content))
					yield "</tr>"
					yield "<tr>"
					yield "<td class='thread'>%s</td>" % render_bbcode(Signature)
					yield "</tr>"
					yield "<tr>"
					if EditTimestamp == None:
						# post wasn't edited
						yield "<td class='thread'>Posted on %s</td>" % time.strftime("%c", time.localtime(Timestamp))
					else:
						# show the username of the post editor
						c = cherrypy.thread_data.db.cursor()
						c.execute('''SELECT User.Username FROM User WHERE User.ID = ?''', (EditUserID,))
						EditUsername = c.fetchone()[0]
						yield "<td class='thread'>Posted on %s, Last Edited on %s by %s</td>" % (time.strftime("%c", time.localtime(Timestamp)), time.strftime("%c", time.localtime(EditTimestamp)), EditUsername)
					yield "</tr>"
					yield "</table>"
					yield "<br />"
					count = count + 1
			yield self.footer()
	default.exposed = True
	
